package com.example.goodpet.utils;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;

import com.example.goodpet.bean.User;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.chat.broadcastreceiver.MessageReceivedReceiver;
import com.example.goodpet.community.bean.UserTieziInfo;
import com.example.goodpet.db.DatabaseHelper;
import com.example.goodpet.db.dao.UserDAO;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseIM;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.interfaces.EaseMessageCallback;
import com.hyphenate.easeui.provider.EaseUserProfileProvider;

import java.util.List;

public class MyApplication extends Application {
    private static final String TAG = MyApplication.class.getSimpleName();
    public static final int PAGE_SIZE=10;
    public static Context context;
    public static Handler handler;
    public static Thread mainThread;
    public static int mainThreadId;
    public static User user;
    public static String location="";
    public static String locationSpecific="菏泽市";
    public static String locationId="010";
    public static double longitude=115.469381;
    public static double latitude=35.246531;
    public static  EMMessageListener msgListener;
    @Override
    public void onCreate() {
        super.onCreate();
        context=getApplicationContext();
        handler=new Handler();
        mainThread=Thread.currentThread();
        mainThreadId=android.os.Process.myTid();
//        CrashHandler.getInstance().init(this);//产品上线时使用

        //EaseIM 初始化
        initEaseIM();
        //获取用户信息
        initUser();

    }

    private  void initEaseIM() {
        EMOptions emOptions = new EMOptions();
        emOptions.setAutoTransferMessageAttachments(true);
        emOptions.setAutoDownloadThumbnail(true);

        if(EaseIM.getInstance().init(context, emOptions)){
            //在做打包混淆时，关闭 debug 模式，避免消耗不必要的资源
            //EMClient.getInstance().setDebugMode(true);

            //EaseIM 初始化成功之后再调用注册消息监听的代码 ...
            msgListener = new EMMessageListener() {

                // 收到消息，遍历消息队列，解析和显示。
                @Override
                public void onMessageReceived(List<EMMessage> messages) {
                    //System.out.println("MyApplication.onMessageReceived 调用了");
                    Log.d(TAG, "onMessageReceived: ");
                    Intent intent=new Intent(MessageReceivedReceiver.BROAD_CAST_MSG_RECEIVED);
                    intent.setPackage(getPackageName());
                    sendBroadcast(intent);
                }

                @Override
                public void onCmdMessageReceived(List<EMMessage> messages) {
                    Log.d(TAG, "onCmdMessageReceived: ");
                }

                @Override
                public void onMessageRead(List<EMMessage> messages) {
                    Log.d(TAG, "onMessageRead: ");
                    Intent intent=new Intent(MessageReceivedReceiver.BROAD_CAST_MSG_RECEIVED);
                    intent.setPackage(getPackageName());
                    sendBroadcast(intent);
                }

                @Override
                public void onMessageDelivered(List<EMMessage> messages) {
                    Log.d(TAG, "onMessageDelivered: ");
                }

                @Override
                public void onMessageRecalled(List<EMMessage> messages) {
                    Log.d(TAG, "onMessageRecalled: ");
                }

                @Override
                public void onMessageChanged(EMMessage message, Object change) {
                    Log.d(TAG, "onMessageChanged: ");
                }
            };
            EMClient.getInstance().chatManager().addMessageListener(msgListener);

        }
        //自定义userProvider
        EaseIM.getInstance().setUserProvider(new EaseUserProfileProvider() {
            @Override
            public EaseUser getUser(String username) {
                String phone=SecurityUtils.unEncryptPhoneNumber(username);
                com.example.goodpet.db.entity.User userDb = getUserFromLocalDb(phone);
                if (userDb!=null){
                    EaseUser easeUser = new EaseUser(username);
                    easeUser.setGender(userDb.getGender());
                    easeUser.setNickname(userDb.getNickname());
                    easeUser.setAvatar(Constants.BASE_URL_IMAGE+userDb.getPortrait());
                    easeUser.setSign(userDb.getSignature());
                    easeUser.setPhone(String.valueOf(userDb.getId()));
                    return easeUser;
                }

                return null;
            }
        });
    }

    /**
     * 从本地数据库获取user数据
     * @param username user的phonenumber
     * @return db.entity.User
     */
    public com.example.goodpet.db.entity.User getUserFromLocalDb(String username){
        return   DatabaseHelper.getInstance(this).getUserDAO().queryUser(username);
    }

    /**
     * 初始化正在使用该app的用户
     */
    private  void initUser() {
        SharedPreferences userInfo = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        long id = userInfo.getLong("id", -1);
        if (id==-1){
            user=null;
        }else {
            User user=new User();
            user.setId(userInfo.getLong("id",-1));
            user.setGender(userInfo.getInt("gender",0));
            user.setNickname(userInfo.getString("nickname","用户"));
            user.setPortrait(userInfo.getString("portrait","http://192.168.0.104:8080/pet/file/image/portrait/moren.png"));
            user.setSignature(userInfo.getString("signature","用一句话展示你的魅力吧！"));
            user.setPhoneNumber(userInfo.getString("phoneNumber",""));
            user.setPassword(userInfo.getString("password",""));
            MyApplication.user=user;
            EMClient.getInstance().login(SecurityUtils.encryptPhoneNumber(user.getPhoneNumber()), user.getPassword(), new EaseMessageCallback() {
                @Override
                public void onSuccess(EMMessage message, int position) {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Log.d("main", "登录聊天服务器成功！");
                }
            });
        }
    }
    /**
     * 保存登录用户
     */
    public static void saveAccount(User user) {
        //保存在MyApplication
        MyApplication.user=user;
        //保存在sp
        SharedPreferences userInfo = context.getSharedPreferences("userInfo", MODE_PRIVATE);
        SharedPreferences.Editor edit = userInfo.edit();
        edit.putLong("id",user.getId());
        edit.putInt("gender",user.getGender());
        edit.putString("password", user.getPassword());
        edit.putString("phoneNumber",user.getPhoneNumber());
        edit.putString("nickname",user.getNickname());
        edit.putString("portrait",user.getPortrait());
        edit.putString("signature",user.getSignature());
        edit.apply();
        //edit.commit();
        //保存在db
        DatabaseHelper.getInstance(context).getUserDAO().insert(new com.example.goodpet.db.entity.User(user.getId(),user.getPhoneNumber(),user.getNickname(),user.getPortrait(),user.getGender(),user.getSignature()));
    }
    /**
     * 更改数据库中的头像
     * @param portrait
     */
    public static void updateMyUserPortrait(String portrait){
        UserDAO userDAO = DatabaseHelper.getInstance(context).getUserDAO();
        userDAO.updatePortrait(user.getId(),portrait);
    }

    /**
     * 更改数据库中的个人信息
     * @param nickname
     * @param signature
     * @param gender
     */
    public static void updateMyUserInfo(String nickname,String signature,int gender){
        UserDAO userDAO = DatabaseHelper.getInstance(context).getUserDAO();
        userDAO.updateInfo(user.getId(),nickname,signature,gender);
    }

    /**
     * 将MyApplication中User转化成UserPetInfo
     * 只有userId，nickname，signature，portrait，phonenumber，gender
     * @return
     */
    public static UserPetInfo fromUserToUserPetInfo(){
        UserPetInfo userPetInfo = new UserPetInfo();
        userPetInfo.setUserId(MyApplication.user.getId());
        userPetInfo.setNickname(MyApplication.user.getNickname());
        userPetInfo.setSignature(MyApplication.user.getSignature());
        userPetInfo.setPortrait(MyApplication.user.getPortrait());
        userPetInfo.setPhoneNumber(MyApplication.user.getPhoneNumber());
        userPetInfo.setGender(MyApplication.user.getGender());
        return userPetInfo;
    }
    /**
     * 将MyApplication中User转化成UserPetInfo
     * 只有userId，nickname，signature，portrait，phonenumber，gender
     * @return
     */
    public static com.example.goodpet.db.entity.User fromUserPetInfoToUser(UserPetInfo userPetInfo){
        com.example.goodpet.db.entity.User user = new com.example.goodpet.db.entity.User();
        user.setId(userPetInfo.getUserId());
        user.setPhoneNumber(userPetInfo.getPhoneNumber());
        user.setPortrait(userPetInfo.getPortrait());
        user.setNickname(userPetInfo.getNickname());
        user.setSignature(userPetInfo.getSignature());
        user.setGender((int)userPetInfo.getGender());
        return user;
    }

    /**
     * 将bean中的userTieziInfo转换成community.bean中的UserTieziInfo
     * @param userTieziInfo
     * @return community.bean中的UserTieziInfo
     */
    public static UserTieziInfo ConvertUserTieziInfoForTransfer(com.example.goodpet.bean.UserTieziInfo userTieziInfo){
        UserTieziInfo userTieziInfo1 = new UserTieziInfo();
        userTieziInfo1.setUserId(userTieziInfo.getUserId());
        userTieziInfo1.setPhoneNumber(userTieziInfo.getPhoneNumber());
        userTieziInfo1.setNickname(userTieziInfo.getNickname());
        userTieziInfo1.setPortrait(userTieziInfo.getPortrait());
        userTieziInfo1.setGender(userTieziInfo.getGender());
        userTieziInfo1.setSignature(userTieziInfo.getSignature());
        userTieziInfo1.setTieziId(userTieziInfo.getTieziId());
        userTieziInfo1.setContent(userTieziInfo.getContent());
        userTieziInfo1.setPostdate(userTieziInfo.getPostdate().toString());
        userTieziInfo1.setLikeNum(userTieziInfo.getLikeNum());
        userTieziInfo1.setMessageNum(userTieziInfo.getMessageNum());
        userTieziInfo1.setTieziImage(userTieziInfo.getTieziImage());
        userTieziInfo1.setCollectNum(userTieziInfo.getCollectNum());
        userTieziInfo1.setLike(userTieziInfo.isLike());
        userTieziInfo1.setCollect(userTieziInfo.isCollect());
        userTieziInfo1.setFoucs(userTieziInfo.isFoucs());
        return userTieziInfo1;

    }
}
